<script setup>
import { ref, reactive, watch } from 'vue'
import multiUpload from '@/components/upload/multiUpload.vue';
import skuImgUpload from '@/components/upload/skuImgUpload.vue';
import TEditor from '@/components/tinymce/TEditor.vue'
import categoryCascader from '@/views/common/categoryCascader.vue'
import { getAttrsByCategoryIdApi } from '@/apis/pms/attribute.js'
import { getSkuMemberLevelApi } from '@/apis/member/memberLevel.js';
import { savepmsApi } from '@/apis/pms/goods.js'
import brandSelect from '@/views/common/brandSelect';

// 上传图片分类
const skuImagesType = "skuImages";

// 步骤条
const active = ref(0)
// sku图片集
const skuImages = ref([])

// 表单数据
const spu = reactive({
  spuTitle: '',
  categoryId: '',
  brandId: '',
  sort: '',
  content: '',
  attrParamsArray: [],
  skus: [],
})

// 数据校验
const rules = reactive({
  spuTitle: [{ required: true, message: '请输入spu名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类名称', trigger: 'blur' }],
  brandId: [{ required: true, message: '请选择分类名称', trigger: 'blur' }],
})

const ruleFormRef = ref()
// 完成第一步,要根据id获取到分类下的商品参数信息
const attrParams = ref([])
const handleCreateOne = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (attrParams.value.length > 0) {
        // 未修改分类获取过直接下一步
        active.value++;
        return;
      } else {
        getAttrsByCategoryIdApi(spu.categoryId, 1)
          .then(res => {
            if (res.code === 0) {
              res.data.forEach(el => {
                attrParams.value.push({
                  attributeId: el.id,
                  attributeName: el.name,
                  selectType: el.selectType,
                  value: el.value,
                  search: 1,
                })
              })
              active.value++;
            }
          })
      }
    } else {
      return false;
    }
  })
}

// 完成第二步,根据分类id获取到分类下的商品规格信息
const attrSales = ref([])
const attrSalesArray = ref([])
const handleCreateTwo = () => {
  if (attrSales.value.length > 0) {
    // 未修改分类获取过直接下一步
    active.value++;
    return;
  } else {
    getAttrsByCategoryIdApi(spu.categoryId, 0)
      .then(res => {
        if (res.code === 0) {
          attrSales.value = res.data;
          attrSales.value.forEach(item => {
            attrSalesArray.value.push({
              attributeId: item.id,
              attributeName: item.name,
              value: [],
            })
          })
          active.value++;
        }
      })
  }
}

// 监听分类id变化获取品牌列表
const categoryPath = ref([])
watch(categoryPath, (newVal, oldVal) => {
  spu.categoryId = newVal[newVal.length - 1];
  spu.attrParamsArray = [];
  attrSales.value = [];
  attrSalesArray.value = [];
})

// 完成第三步,生成每个sku表单数据
const tableColumnData = ref([])
const handleCreateThree = () => {
  // 传递生成笛卡尔积的数组
  let valueAmass = [];
  // 清空tableColumnData不然会叠加属性组合
  tableColumnData.value = [];
  attrSalesArray.value.forEach(item => {
    if (item.value.length > 0) {
      valueAmass.push(item.value)
      tableColumnData.value.push(item);
    }
  })

  if (valueAmass.length === 0) {
    ElMessage({
      message: '未选择商品的销售属性',
      type: 'warning',
    })
    return;
  }

  // 生成笛卡尔积
  let result = cartesianpms(valueAmass)
  let skus = [];
  // 根据笛卡儿积生成对应的sku
  result.forEach(item => {
    let attrArray = []; // sku属性组
    item.forEach((el, index) => {
      attrArray.push({
        attributeId: tableColumnData.value[index].attributeId,
        attributeName: tableColumnData.value[index].attributeName,
        value: el,
      })
    })

    // 判断是否生成过（点击返回了上一步）
    let res = hasAndReturnSku(spu.skus, item);
    if (res === null) {
      // 生成图片信息
      const imgs = handleSelectImages();
      // 生成会员信息
      // const members = handleCreateMember();
      // 生成每个sku信息
      skus.push({
        attribute: attrArray,    // 属性集合
        skuTitle: spu.spuTitle + " " + item.join(" "),  // 商品标题(spuTitle + 拼接的属性集合)
        subTitle: '',
        price: 0.00,   // 价格
        images: [],   // 已选择的图集
        skuDefaultImg: '',
        selectImages: imgs, // 可选择的图集
        stock: 0,  // 库存数
        stockLocked: 0, // 锁定库存数
        fullReductions: [{
          mark: 1, // 删除标识
          fullPrice: 0,   // 满多少
          reducePrice: 0.00, // 减多少
        }],
        ladders: [{
          mark: 1, // 删除标识
          count: 0,    // 满几件
          discount: 1.00,  // 打几折，1不打折
        }],
        // memberPrice: members, // 会员列表(删除了会员价)
        descar: item, // 笛卡儿积的标识
      })
    } else {
      skus.push(res);
    }
  })
  spu.skus = skus;
  // console.log(result)
  // console.log(tableColumnData.value)
  active.value++;
}

// 生成笛卡儿积
const cartesianpms = (arrays) => {
  return arrays.reduce((a, b) => {
    let ret = [];
    a.forEach(a => {
      b.forEach(b => {
        ret.push(a.concat([b]));
      });
    });
    return ret;
  }, [[]]);
}

// 生成选择图片集合
const handleSelectImages = () => {
  let selectImages = [];
  skuImages.value.forEach(item => {
    selectImages.push({
      imgUrl: item.url,
      skuDefaultImg: 0,
    })
  })
  return selectImages;
}


// 查看是否已经生成过sku
const hasAndReturnSku = (skus, descar) => {
  let res = null;
  if (skus.length > 0) {
    for (let i = 0; i < skus.length; i++) {
      if (skus[i].descar.join(" ") == descar.join(" ")) {
        res = skus[i];
      }
    }
  }
  return res;
}

// 输入新值显示框和过渡值
const inputVisible = ref([])
const inputValSale = ref('')
// 输入新值
const handleInputConfirm = (index) => {
  console.log(index)
  if (inputValSale.value !== null && inputValSale.value !== void 0 && inputValSale.value !== '') {
    attrSales.value[index].value = attrSales.value[index].value + ';' + inputValSale.value;
    inputValSale.value = '';
  }
  inputVisible.value[index] = false;
}

// 展示输入框
const showInput = (index) => {
  inputVisible.value[index] = true;
}

// 删除不需要的某个sku
const handleRemoveSku = (descar) => {
  const index = spu.skus.findIndex(item => item.descar === descar);
  if (index === -1) {
    return;
  } else {
    spu.skus.splice(index, 1);
  }
}

// 解决修改数据时，table表格的展开行自动收起
const getRowKey = (row) => {
  return row.descar;
}
// 表格手风琴模式
const expands = ref([])
const expndChange = (row, expandedRows) => {
  if (expandedRows.length) {
    expands.value = []
    if (row) {
      expands.value.push(row.descar) // 每次push进去的是每行的ID
    }
  } else {
    expands.value = [] // 默认不展开
  }
}

// 设置默认图片
const handleSelectDefaultImg = (sku, index) => {
  sku.selectImages.forEach(el => { el.skuDefaultImg = 0; })
  sku.selectImages[index].skuDefaultImg = 1;
  sku.skuDefaultImg = sku.selectImages[index].imgUrl;
}

const activeName = ref('first')
// 添加满减
const handleAddFullReduction = (fullReduction, mark) => {
  // 最多两个满减
  if (fullReduction.length === 2) {
    ElMessage({
      message: '最多设置两个满减信息',
      type: 'warning',
    })
    return;
  } else {
    fullReduction.push(
      {
        mark: mark + 1,  // 防止标识重复
        fullPrice: 0,
        reducePrice: 0.00,
      }
    )
  }
}

// 删除满减
const handleRemoveFullReduction = (fullReduction, mark) => {
  // 最少留一个
  if (fullReduction.length === 1) {
    ElMessage({
      message: '最少保留一个,不设置则默认无满减',
      type: 'warning',
    })
    return;
  }
  const index = fullReduction.findIndex(item => item.mark === mark);
  if (index === -1) {
    return;
  } else {
    fullReduction.splice(index, 1);
  }
}

// 添加折扣
const handleAddLadder = (ladder, mark) => {
  // 最多两个满减
  if (ladder.length === 2) {
    ElMessage({
      message: '最多设置两个折扣信息',
      type: 'warning',
    })
    return;
  } else {
    ladder.push(
      {
        mark: mark + 1,  // 防止标识重复
        count: 0,    // 满几件
        discount: 1.00,  // 打几折，1不打折
      }
    )
  }
}

// 删除折扣
const handleRemoveLadder = (ladder, mark) => {
  // 最少留一个
  if (ladder.length === 1) {
    ElMessage({
      message: '最少保留一个,不设置则默认无折扣',
      type: 'warning',
    })
    return;
  }
  const index = ladder.findIndex(item => item.mark === mark);
  if (index === -1) {
    return;
  } else {
    ladder.splice(index, 1);
  }
}

// 查看上一步
const handlebeforeStep = () => {
  active.value--;
}

// 保存商品
const visibleStatus = ref(2)
const handleOver = () => {
  if (spu.skus.length === 0) {
    ElMessage({
      message: '无可保存商品信息',
      type: 'warning',
    })
    return;
  }
  //确保每个skus都有图片
  let imageMark = 0;
  spu.skus.forEach(el => {
    if (el.images.length === 0) {
      imageMark = 1;
    }
  })
  if (imageMark === 1) {
    ElMessage({
      message: '有商品未选择图片，请进行选择',
      type: 'warning',
    })
    return;
  }
  spu.attrParamsArray.forEach(el => {
    if (el.inputVal instanceof Array) {
      el.value = el.inputVal.join('；');
      delete el.inputVal;
    } else {
      el.value = el.inputVal;
      delete el.inputVal;
    }
  })
  // console.log(spu.attrParamsArray)
  // 处理sku
  spu.skus.forEach(el => {
    // 删除笛卡儿积
    delete el.descar;
    // 删除可选图片
    delete el.selectImages;
  })
  savepmsApi(spu)
    .then(res => {
      if (res.code === 0) {
        // 保存成功
        active.value++;
        visibleStatus.value = 0;
        skuImages.value = [];
      } else {
        // 保存失败
        active.value++;
        visibleStatus.value = 1;
      }
    })
}

// 继续保存
const editor = ref()
const category = ref()
const handleAfresh = () => {
  spu.spuTitle = '';
  spu.categoryId = '';
  spu.brandId = '';
  spu.sort = '';
  spu.content = '';
  editor.value.modelValue = '';
  category.value.cascaderPath=[];
  spu.attrParamsArray = [];
  spu.skus = [];
  active.value = 0;
}
</script>

<template>
  <el-col :span="24">
    <el-steps :active="active" finish-status="success">
      <el-step title="基本信息" />
      <el-step title="商品参数" />
      <el-step title="销售属性" />
      <el-step title="详细信息" />
      <el-step title="保存状态" />
    </el-steps>
  </el-col>

  <!-- 第一步 -->
  <el-col :span="24" v-show="active === 0">
    <el-card class="box-card from_css">
      <el-form :model="spu" label-width="120px" :rules="rules" ref="ruleFormRef">
        <el-form-item label="商品标题" prop="spuTitle">
          <el-input v-model="spu.spuTitle" style="width: 60%;" placeholder="请输入商品标题" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <categoryCascader v-model:categoryPath="categoryPath" style="width: 30%;" ref="category"/>
        </el-form-item>
        <el-form-item label="所属品牌" prop="brandId">
          <brandSelect v-model:brandId="spu.brandId" v-model:categoryId="spu.categoryId" style="width: 30%;">
          </brandSelect>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="spu.sort" :min="0" style="width: 40%;" />
        </el-form-item>
        <el-form-item label="商品图集">
          <multiUpload v-model:imageList="skuImages" :uploadType="skuImagesType"></multiUpload>
        </el-form-item>
        <el-form-item label="商品介绍">
          <TEditor v-model:content="spu.content" ref="editor"></TEditor>
        </el-form-item>
        <el-form-item>
          <div class="next_css">
            <el-button type="primary" @click="handleCreateOne(ruleFormRef)">下一步</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </el-col>

  <!-- 第二步 -->
  <el-col :span="24" v-show="active === 1">
    <el-card class="box-card from_css">
      <h2 class="two_h2">选择商品参数</h2>
      <el-checkbox-group v-model="spu.attrParamsArray" class="two_checkbox_group">
        <div v-for="item in attrParams" class="two_div">
          <el-checkbox :label="item" style="height: 60px;border-radius: 10px;padding: 10px;">
            <span>{{ item.attributeName }}</span>
          </el-checkbox>
          <el-select v-model="item.inputVal" :multiple="item.selectType === 1" filterable allow-create
            default-first-option :reserve-keyword="false" placeholder="选择或输入商品参数"
            style="margin-left: 1%;margin-right: 1%;width: 100%;">
            <el-option v-for="(el, index) in item.value.split(';')" :key="index" :label="el" :value="el" />
          </el-select>
          <div style="width: 240px;display: flex;justify-content: flex-end;align-items: center;padding-right: 10px;">
            <el-text style="margin-right: 5px;">参与检索</el-text>
            <el-switch @click.stop v-model="item.search" inline-prompt active-text="是" inactive-text="否" :active-value="0"
              :inactive-value="1" />
          </div>
        </div>
      </el-checkbox-group>
      <div class="next_css">
        <el-button type="info" @click="handlebeforeStep">上一步</el-button>
        <el-button type="primary" @click="handleCreateTwo">下一步</el-button>
      </div>
    </el-card>
  </el-col>

  <!-- 第三步 -->
  <el-col :span="24" v-show="active === 2">
    <el-card class="box-card from_css">
      <h2 style="width: 100%;text-align: center;margin-bottom: 10px;">选择销售属性</h2>
        <div v-for="(item, index) in attrSales" :key="item.id">
          <div style="margin-bottom: 3px;">{{ item.name }}</div>
          <el-checkbox-group v-model="attrSalesArray[index].value">
            <el-checkbox v-for="val in item.value.split(';')" :label="val" border style="margin-bottom: 15px;" />
            <div style="margin-left: 20px;display: inline;">
              <el-button v-if="!inputVisible[index]" size="mini" style="margin-bottom: 14px;" @click="showInput(index)">
                +自定义
              </el-button>
              <el-input v-if="inputVisible[index]" v-model="inputValSale"
                style="width: 150px;margin-bottom: 14px;" @keyup.enter.native="handleInputConfirm(index)" @blur="handleInputConfirm(index)">
              </el-input>
            </div>
          </el-checkbox-group>
        </div>
        <div>
          <div class="next_css">
            <el-button type="info" @click="handlebeforeStep">上一步</el-button>
            <el-button type="primary" @click="handleCreateThree">下一步</el-button>
          </div>
        </div>
    </el-card>
  </el-col>

  <!-- 第四步 -->
  <el-col :span="24" v-show="active === 3">
    <el-card class="box-card from_css">
      <el-table :data="spu.skus" style="width: 100%" :row-key="getRowKey" :expand-row-keys="expands"
        @expand-change="expndChange">
        <el-table-column label="属性组合">
          <el-table-column v-for="(item, index) in tableColumnData" :label="item.name" :key="item.id">
            <template v-slot="scope">
              <span style="margin-left: 10px">{{ scope.row.attribute[index].value }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="sku标题" prop="skuTitle">
          <template v-slot="scope">
            <el-input v-model="scope.row.skuTitle"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="副标题" prop="subTitle">
          <template v-slot="scope">
            <el-input v-model="scope.row.subTitle"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" prop="price">
          <template v-slot="scope">
            <el-input v-model="scope.row.price"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="商品库存" prop="stock">
          <template v-slot="scope">
            <el-input v-model="scope.row.stock"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="锁定库存数" prop="stockLocked">
          <template v-slot="scope">
            <el-input v-model="scope.row.stockLocked"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" align="center">
          <template v-slot="scope">
            <el-button plain @click="handleRemoveSku(scope.row.descar)">删除</el-button>
          </template>
        </el-table-column>
        <!-- 展开内容 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <div style="width:100%;">
              <div style="width: 100%;padding-left: 8px;">
                <h3>选择商品的图集</h3>
              </div>
              <el-checkbox-group v-model="scope.row.images" class="four_checkbox_group">
                <el-card v-for="(item, index) in scope.row.selectImages" :body-style="{ padding: '0px', height: '240px' }"
                  class="four_card">
                  <img :src="item.imgUrl" class="image" style="width:100%;height: 80%;" />
                  <div class="four_div">
                    <el-checkbox :label="item" class="four_button" style="margin-left:5px;" border>选择</el-checkbox>
                    <el-button plain class="four_button"
                      v-if="scope.row.images.includes(item) && item.skuDefaultImg === 0"
                      @click="handleSelectDefaultImg(scope.row, index)">设为默认</el-button>
                    <el-button type="primary" v-if="scope.row.images.includes(item) && item.skuDefaultImg === 1"
                      class="four_button">
                      <el-icon style="margin-right:5px;">
                        <SuccessFilled />
                      </el-icon>默认图片
                    </el-button>
                  </div>
                </el-card>
                <!-- 继续上传按钮，单独给个组件 -->
                <el-card shadow="always" :body-style="{ padding: '0px', height: '240px' }" class="four_card">
                  <skuImgUpload v-model:selectImages="scope.row.selectImages" :uploadType="skuImagesType"></skuImgUpload>
                </el-card>
              </el-checkbox-group>
              <div style="width: 100%;margin-top: 10px;padding-left: 8px;">
                <h3>设置优惠的信息</h3>
              </div>
              <div style="width: 100%;padding: 10px;margin-bottom:15px;">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                  <el-tab-pane label="满减" name="first">
                    <el-table :data="scope.row.fullReductions" border>
                      <el-table-column label="满多少">
                        <template v-slot="scoped">
                          <el-input-number v-model="scoped.row.fullPrice" :min="0" :step="1" style="width:230px;" />
                        </template>
                      </el-table-column>
                      <el-table-column label="减多少">
                        <template v-slot="scoped">
                          <el-input-number v-model="scoped.row.reducePrice" :precision="2" :min="0" :step="1"
                            style="width:230px;" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="170" align="center">
                        <template v-slot="scoped">
                          <el-button plain
                            @click="handleAddFullReduction(scope.row.fullReductions, scoped.row.mark)">添加</el-button>
                          <el-button plain
                            @click="handleRemoveFullReduction(scope.row.fullReductions, scoped.row.mark)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                  <el-tab-pane label="折扣" name="second">
                    <el-table :data="scope.row.ladders" border>
                      <el-table-column label="满几件">
                        <template v-slot="scoped">
                          <el-input-number v-model="scoped.row.count" :min="0" :step="1" style="width:230px;" />
                        </template>
                      </el-table-column>
                      <el-table-column label="打几折(1-不打折,0.1-打一折)">
                        <template v-slot="scoped">
                          <el-input-number v-model="scoped.row.discount" :precision="2" :min="0" :max="1" :step="0.1"
                            style="width:230px;" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="170" align="center">
                        <template v-slot="scoped">
                          <el-button plain @click="handleAddLadder(scope.row.ladders, scoped.row.mark)">添加</el-button>
                          <el-button plain @click="handleRemoveLadder(scope.row.ladders, scoped.row.mark)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </template>
        </el-table-column>

      </el-table>
      <div style="width: 100%; text-align: center;margin-top: 10px;">
        <el-button type="info" @click="handlebeforeStep">上一步</el-button>
        <el-button type="primary" @click="handleOver">保存商品</el-button>
      </div>
    </el-card>
  </el-col>

  <!-- 第五步 -->
  <el-col :span="24" v-if="active === 4">
    <el-card class="box-card from_css">
      <div v-if="visibleStatus === 0" style="height: 150px;width: 100%;">
        <div style="width: 100%;text-align: center;font-size: 25px;height: 110px;">
          <img src="@/images/success.png" style="height: 100%;" />
        </div>
        <div style="width: 100%;text-align: center;font-size: 25px;height: 50px;line-height: 50px;">
          <el-button type="success" @click="handleAfresh">保存成功-继续保存</el-button>
        </div>
      </div>

      <div v-if="visibleStatus === 1" style="height: 150px;width: 100%;">
        <div style="width: 100%;text-align: center;font-size: 25px;height: 110px;">
          <img src="@/images/fail.png" style="height: 100%;" />
        </div>
        <div style="width: 100%;text-align: center;font-size: 25px;height: 50px;line-height: 50px;">
          <el-button type="danger" @click="handleAfresh">保存失败-重新保存</el-button>
        </div>
      </div>
    </el-card>
  </el-col>
</template>

<style scoped lang='scss'>
.from_css {
  width: 96%;
  margin: 10px auto;
}

.next_css {
  width: 100%;
  text-align: center;
  margin-top: 10px;
}

.two_h2 {
  width: 100%;
  text-align: center;
  margin-bottom: 10px;
}

.two_checkbox_group {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.two_div {
  width: calc(50% - 2%);
  margin: 1%;
  height: 60px;
  display: flex;
  align-items: center;
  border: 1px solid #a6a9ad;
  border-radius: 10px;
}

.four_checkbox_group {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.four_card {
  width: calc(20% - 2%);
  margin: 1%;
  box-sizing: border-box;
}

.four_div {
  width: 100%;
  height: 20%;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.four_button {
  height: 60%;
  margin-right: 2%;
  margin-bottom: 2%
}

.four_input_number {
  width: 80%;
  margin: 0 5px;
}
</style>